/**
 * UserRefRoleController.java
 */
package org.yate.oa.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.math.NumberUtils;
import org.yate.oa.model.RoleEntity;
import org.yate.oa.model.UserEntity;
import org.yate.oa.model.UserRefRoleEntity;
import org.yate.oa.service.IRoleService;
import org.yate.oa.service.IUserRefRoleService;
import org.yate.oa.service.IUserService;
import org.yate.oa.utils.Pagination;

/**
 * @author Yate
 * @date Nov 20, 2013
 * @description TODO
 * @version 1.0
 */
@WebServlet(urlPatterns = { "/role/setting" }, asyncSupported = true)
public class UserRefRoleController extends BaseServletController {

	private IRoleService roleService;
	private IUserService userService;
	private IUserRefRoleService userRefRoleService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.yate.oa.controller.BaseController#init(javax.servlet.ServletConfig
	 * )
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		this.roleService = (IRoleService) this.springCtx.getBean("roleService");
		this.userService = (IUserService) this.springCtx.getBean("userService");
		this.userRefRoleService = (IUserRefRoleService) this.springCtx
				.getBean("userRefRoleService");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		long rid = NumberUtils.toLong(req.getParameter("rid"));

		RoleEntity r = this.roleService.getEntity(rid);
		req.setAttribute("r", r);

		Pagination<UserEntity> u = this.userService.getEntities(1,
				Integer.MAX_VALUE, "", "");
		req.setAttribute("ud", u);

		List<UserRefRoleEntity> urr = this.userRefRoleService
				.getEntityByRoleId(rid);
		req.setAttribute("urrd", urr);

		req.getRequestDispatcher("/jsp/roles/urr.jsp").forward(req, resp);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest
	 * , javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		long rid = NumberUtils.toLong(req.getParameter("roleId"));
		String[] ur = req.getParameterValues("ur");
		
		this.userRefRoleService.removeByRoleId(rid);

		this.userRefRoleService.batchAdd(rid, ur);

		req.getRequestDispatcher("/role/get").forward(req, resp);
	}

}
